package com.henrybit.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.henrybit.annotation.Overload;
import com.henrybit.entity.MenuInfo;
import com.henrybit.exception.DBException;
import com.henrybit.util.Constant;
import com.henrybit.util.DBFactory;

/**
 * 菜单Dao<p>
 * @author henrybit
 * version 1.0
 */
public class MenuDao extends BaseDao<MenuInfo> {

	/**查询基础SQL*/
	private static String queryPre = "select * from menu_list where 1=1";
	/**分页默认大小*/
	private static int pageSize = 6;
	/**分页编号*/
	private static int pageNo = 1;
	
	@Override
	public List<MenuInfo> query(MenuInfo t) throws DBException {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Overload
	public List<MenuInfo> query(MenuInfo t, int page) throws DBException {
		List<MenuInfo> list = new ArrayList<MenuInfo>();
		String sql = prepareQuerySql(t);
		Connection con = DBFactory.getConnection();
		PreparedStatement ps = null;
		try {
			con.setAutoCommit(false);
			ps = con.prepareStatement(sql);
			ResultSet rs = ps.getResultSet();
			while(rs.next()) {
				MenuInfo menuInfo = getMenuInfo(rs);
				list.add(menuInfo);
			}
			rs.close();
			ps.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new DBException(e, Constant.DB_QUERY_MENU_INFO_ERROR, "准备酒店菜单SQL执行异常");
		} finally {
			try {
				con.close();
			} catch(SQLException e) {
				throw new DBException(e, Constant.DB_CONNECTION_CLOSE_ERROR, "关闭数据库连接异常");
			}
		}
		return list;
	}
	
	@Override
	public void insert(MenuInfo t) throws DBException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean update(MenuInfo t) throws DBException {
		// TODO Auto-generated method stub
		return false;
	}
	
	private String prepareQuerySql(MenuInfo t) {
		int menuId = t.getMenuId();
		String menuName = t.getMenuName();
		StringBuilder sql = new StringBuilder(queryPre);
		if(menuId > 0) {
			sql.append(" and menuId=").append(menuId);
		}
		if(menuName != null && !menuName.equals("")) {
			sql.append(" and menuName like '%").append(menuName).append("%'");
		}
		return sql.toString();
	}
	
	private MenuInfo getMenuInfo(ResultSet rs) throws DBException {
		MenuInfo menuInfo = new MenuInfo();
		try {
			int menuId = rs.getInt("menuId");
			String menuName = rs.getString("menuName");
			String menuUrl = rs.getString("menuUrl");
			int parentId = rs.getInt("parentId");
			menuInfo.setMenuId(menuId);
			menuInfo.setMenuName(menuName);
			menuInfo.setMenuUrl(menuUrl);
			menuInfo.setParentId(parentId);
		} catch (Exception e) {
			throw new DBException(e, Constant.DB_MENU_PREPARE_DATA_ERROR, "封装菜单信息异常");
		}
		return menuInfo;
	}
}
